using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace Programonica.Igramonica.LandscapeClasses
{
    public class Primitive
    {
        public Vector3 Vertex1;
        public Vector3 Vertex2;
        public Vector3 Vertex3;

        public Plane Plane
        {
            get
            {
                return new Plane(Vertex1, Vertex3, Vertex2);
            }
        }

        public Vector3 Normal
        {
            get
            {
                return Plane.Normal;
            }
        }

        public Vector3 Barycentric
        {
            get
            {
                float p = 1.0f / 3.0f;

                return Vector3.Barycentric(Vertex1, Vertex2, Vertex3, p, p);
            }
        }

        public Primitive()
        {

        }

        public Primitive(Vector3 vertex1, Vector3 vertex2, Vector3 vertex3)
        {
            this.Vertex1 = vertex1;
            this.Vertex2 = vertex2;
            this.Vertex3 = vertex3;
        }

        public static bool SameSide(Vector3 p1, Vector3 p2, Vector3 a, Vector3 b)
        {
            Vector3 cp1 = Vector3.Cross(b - a, p1 - a);
            Vector3 cp2 = Vector3.Cross(b - a, p2 - a);
            if (Vector3.Dot(cp1, cp2) >= 0.0f)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool PointInTriangle(Vector3 point, Primitive tri)
        {
            if ((SameSide(point, tri.Vertex1, tri.Vertex2, tri.Vertex3)) &&
                (SameSide(point, tri.Vertex2, tri.Vertex1, tri.Vertex3)) &&
                (SameSide(point, tri.Vertex3, tri.Vertex1, tri.Vertex2)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
